/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.soap;

import com.jmooc.entity.Course;
import com.jmooc.entity.User;
import com.jmooc.entity.UserCertification;
import com.jmooc.service.CourseService;
import com.jmooc.service.UserCertificationService;
import com.jmooc.service.UserService;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;


@WebService(serviceName = "soap/quizz")
public class QuizzWebService {
    
    @EJB
    private UserService userService;
    
    @EJB
    private UserCertificationService userCertificationService;
    
    @EJB
    private CourseService courseService;

    // Quizz passed = certification obtained
    @WebMethod(operationName = "pass")
    public boolean pass(@WebParam(name = "token") String token, @WebParam(name = "courseId") Long courseId) {
        User user = userService.getUserByToken(token);
        
        if (user == null)
            return false;
        
        boolean hasCourseCertifications = false;
                
        List<UserCertification> certifications = userCertificationService.getAllByUser(user);
        Course course = courseService.getById(courseId);

        for (Iterator<UserCertification> it = certifications.iterator(); it.hasNext();) {
            UserCertification userCertification = it.next();

            if (userCertification.getCourse().equals(course))
                hasCourseCertifications = true;
        }   

        if (!hasCourseCertifications) {
            UserCertification certification = new UserCertification();
            certification.setCourse(course);
            certification.setUser(user);
            certification.setObtentionDate(new Date());
            userCertificationService.create(certification);
        }
        
        return true;
    }
    
    // Quizz passed = certification obtained
    @WebMethod(operationName = "print")
    public boolean print(@WebParam(name = "token") String token, @WebParam(name = "courseId") Long courseId) {
        User user = userService.getUserByToken(token);
        
        if (user == null)
            return false;
        
        List<UserCertification> certifications = userCertificationService.getAllByUser(user);
        
        for (Iterator<UserCertification> it = certifications.iterator(); it.hasNext();) {
            UserCertification userCertification = it.next();
            
            if (userCertification.getCourse().getId() == courseId) {
                userCertificationService.print(userCertification);
                return true;
            }
        }
        
        return false;
    }
}
